import { useState, useEffect } from "react";
import useGetUserInfo from "./useGetUserInfo";
import { useRequest } from "ahooks";
import { getUserInfoService } from "../service/user";
import { useDispatch } from "react-redux";
import { loginReducer } from "../store/userReducer";

function useLoadUserData() {
  const dispatch = useDispatch()
  const [waitingUserData, setWaitingData] = useState(true)

  const {run} = useRequest(getUserInfoService,{
    manual:true,
    onSuccess(result) {
      const {username, nickname} = result
      //存储到redux
      dispatch(loginReducer({ username,nickname }))
    },
    onFinally(){
      setWaitingData(false)
    }
  })
  //获取当前用户信息
  const { username } =  useGetUserInfo()
  //判断是否拥有用户信息
  useEffect(() => {
    if(username){
      setWaitingData(false)
      return
    }
    run()
  },[username])

  return { waitingUserData }
}

export default useLoadUserData;